const fs = require("fs"); // 系统模块 无需安装
const path = require("path"); // 系统模块 无需安装
const { addLog } = require("../utils");
const { exec } = require("child_process");

// addLog("判断是否有project",projectName)    
function isProject(projectName){
  // 判断是否有project
  const files = fs.readdirSync(path.join(__dirname, "../../src/project")).filter(item=>item != '.DS_Store');
  // 判断projectName下面是否有.git文件 如果有才是true
  return files.includes(projectName) && fs.existsSync(path.join(__dirname, "../../src/project", projectName,'.git'))
}

// clone 项目../../src/project/projectName/下面
function gitClone(projectName,gitAddress,gitBranch,installType){
  // 判断是否有projectName文件夹如果没有就创建有执行pull
  if (isProject(projectName)) {
    return gitPull(projectName,gitAddress,gitBranch)
  }else{
    // 判断是否有projectName文件夹没有就创建
    if (!fs.existsSync(path.join(__dirname, "../../src/project", projectName))) {
      fs.mkdirSync(path.join(__dirname, "../../src/project", projectName));
    }
  }
  // clone 项目
  const cmdStr = `cd ${path.join(
    __dirname,
    "../../src/project",
    projectName
  )} && git clone ${gitAddress} . && git checkout ${gitBranch}`;
  return new Promise((resolve,reject)=>{
    exec(cmdStr,(err,stdout,stderr)=>{
      if(err){
        reject('git clone 失败'+err)
      }else{
        const cmdStr2 = `cd ${path.join(
          __dirname,
          "../../src/project", 
          projectName
        )} && ${installType}`;
        addLog(`${installType} 开始`,projectName)
        exec(cmdStr2,(err,stdout,stderr)=>{
          if(err){
            reject(`${installType} 失败`+err)
          }else{
            resolve('git clone 成功')
          }
        })
      }
    })

  })
}

// git pull 更新项目
function gitPull(projectName,gitAddress,gitBranch,installType){
  // 判断是否有projectName文件夹没有执行clone
  if (!isProject(projectName)) {
    return gitClone(projectName,gitAddress,gitBranch)
  }
  // git pull 更新项目
  const cmdStr = `cd ${path.join(
    __dirname,
    "../../src/project",
    projectName
  )} &&  git pull`
  return new Promise((resolve,reject)=>{
    exec(cmdStr,(err,stdout,stderr)=>{
      if(err){
        reject('git pull 失败：'+err)
      }else{
        //  判断package.json是否有变动
        if(stdout.includes('package.json')){
          //  有变动执行npm install
          const cmdStr2 = `cd ${path.join(
            __dirname,
            "../../src/project",
            projectName
          )} && ${installType}`;
          addLog(`package.json 变动重新 ${installType}`,projectName)
          exec(cmdStr2,(err,stdout2,stderr)=>{
            if(err){
              reject(`${installType} 失败`+err)
            }else{
              addLog(`${installType} 成功`)
              resolve('git pull 成功')
            }
          })
        }else{
          addLog('git pull 成功---更新信息：  '+stdout,projectName)
          resolve('git pull 成功')
        }
      }
    })
  })
}

function initProject({projectName,gitAddress,gitBranch},{installType}){

  let installTypeUtil = installType.split(' ')[0]
  // 判断当前环境是否有installTypeUtil全局环境
  const cmdStr = `${installTypeUtil} -v`;
  return new Promise((resolve,reject)=>{
    exec(cmdStr,(err,stdout,stderr)=>{
      if(err){
        addLog(`${installTypeUtil} 环境未安装`,projectName,'error')
        // 安装
        const cmdStr2 = `npm install -g ${installTypeUtil}`;
        addLog(`${installTypeUtil} 开始安装`,projectName)
        exec(cmdStr2,(err,stdout,stderr)=>{
          if(err){
            addLog(`${installTypeUtil} 安装失败${err}`,projectName,'error')
            reject(`${installTypeUtil} 安装失败${err}`)
          }else{
            addLog(`${installTypeUtil} 安装成功`,projectName)
            gitFn(projectName,gitAddress,gitBranch,installType).then(resolve).catch(reject)
          }
        })
      }else{
        gitFn(projectName,gitAddress,gitBranch,installType).then(resolve).catch(reject)
      }
    })
  })
}

function gitFn(projectName,gitAddress,gitBranch,installType){
  return new Promise((resolve,reject)=>{
    if(isProject(projectName)){
      addLog("git pull 更新项目",projectName)
      gitPull(projectName,gitAddress,gitBranch,installType).then((e)=>{
        addLog(e,projectName)
        resolve(true)
      }).catch((e)=>{
        addLog(e+'git拉取报错删除project 重新git clone',projectName,'error')
        // reject(false)
        // 删除project 重新git clone
        const cmdStr = `rm -rf ${path.join(
          __dirname,
          "../../src/project",
          projectName
        )}`;
        addLog(`删除project`,projectName)
        exec(cmdStr,(err,stdout,stderr)=>{
          if(err){
            addLog(`删除project失败${err}`,projectName,'error')
            reject(`${installTypeUtil} 安装失败${err}`)
          }else{
            addLog(`删除project成功，重新clone项目`,projectName)
            gitClone(projectName,gitAddress,gitBranch,installType).then((e)=>{
              addLog(e,projectName)
              resolve(true)
            }).catch((e)=>{
              addLog(e,projectName,'error')
              reject(false)
            })
          }
        })
      })
    }else{
      addLog("git clone 项目",projectName)
      gitClone(projectName,gitAddress,gitBranch,installType).then((e)=>{
        addLog(e,projectName)
        resolve(true)
      }).catch((e)=>{
        addLog(e,projectName,'error')
        reject(false)
      })
    }
  })
}


module.exports = {

  initProject

};
